package com.jsle.financial.action;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.jsle.financial.domain.Company_Resources;
import com.jsle.financial.domain.User;
import com.jsle.financial.domain.UserGroup;
import com.jsle.financial.domain.User_UserGroups;
import com.jsle.financial.service.UserService;
import com.jsle.financial.util.AJAXUtil;
import com.jsle.financial.util.Constants;
import com.jsle.financial.util.Tools;
import com.jsle.financial.vo.Page;
import com.jsle.financial.vo.Result;

/**
 * 用户管理Controller
 * @author wisdying
 * @date 2012-10-26
 */
@Controller
@RequestMapping("/user")
public class UserInfoController {
	private Log log = LogFactory.getLog(LoginController.class);
	@Resource
	private UserService userService;
	
	/**
	 * 保存用户
	 */
	@RequestMapping(value = "/addUser.do",method=RequestMethod.POST)
	@ResponseBody
	public void addUser(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String userId = WebUtils.findParameterValue(request, "userId");
		String loginName = WebUtils.findParameterValue(request, "loginName");
		String cNName = WebUtils.findParameterValue(request, "cNName");
		String loginPassword = WebUtils.findParameterValue(request, "loginPassword");
		String companyCode = WebUtils.findParameterValue(request, "companyCode");
		String companyName = WebUtils.findParameterValue(request, "companyName");
		String positionName = WebUtils.findParameterValue(request, "positionName");
		String positionCode = WebUtils.findParameterValue(request, "positionCode");
		String userType = WebUtils.findParameterValue(request, "userType");
		String userGroup = WebUtils.findParameterValue(request, "userGroup");
		
		User user = new User();
		
		user.setLoginName(loginName);
		user.setLoginPassword(loginPassword);
		user.setcNName(cNName);
		user.setPositionName(positionName);
		user.setPositionCode(positionCode);
		user.setUserType(Integer.valueOf(userType));
		user.setCompanyName(companyName);
		user.setCompanyCode(companyCode);
		
		Result rs = new Result();
		if(userId != null && !userId.equals("")){
			user.setId(Integer.valueOf(userId));
			rs = userService.updateUser(user);
		}else{
			rs = userService.addUser(user);
		}
		 
		if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			Page page = new Page(0,1);
			rs = userService.queryUsersByPage(page,loginName);
			if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				user = (User)((Page)rs.getResultValue()).getData().get(0);
				if(userGroup!=null && !userGroup.equals("")){
					String [] resourceIdStrArrs = userGroup.split(",");//页面传入的资源id字符串切割获取资源id字符数组
					//用户组id字符数组封装成用户组id整型集合
					List<Integer> resourceIds = new ArrayList<Integer>();
					
					if(resourceIdStrArrs.length == 0){
						resourceIds.add(Integer.valueOf(userGroup));
					}else{
						for(String id : resourceIdStrArrs){
							resourceIds.add(Integer.valueOf(id));
						}
					}
					//循环添加用户配置用户组
					List<User_UserGroups> list = getListCompanyResourcesByIds(user.getId(),resourceIds);
					
					//如果是修改，则先删除之前用户组，再次重新添加
					if(userId != null && !userId.equals("")){
						User_UserGroups uug = new User_UserGroups();
						uug.setUserId(user.getId());
						rs = userService.delUserAndUserGroups(uug);
					}
					for(User_UserGroups uug : list){
						rs = userService.addUserAndUserGroups(uug);
					}
					if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
						AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
					}else{
						AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
					}
				}else{
					//如果是修改，没有选择用户组，则删除之前的用户组
					if(userId != null && !userId.equals("")){
						User_UserGroups uug = new User_UserGroups();
						uug.setUserId(user.getId());
						rs = userService.delUserAndUserGroups(uug);
					}
					AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
				}
			}
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
	}
	/**
	 * 删除单个用户
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/delUser.do",produces = "application/json")
	@ResponseBody
	public void delUser(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String userId = WebUtils.findParameterValue(request, "userId");
		
		User user = new User();
		user.setId(Integer.valueOf(userId));
		
		Result rs = new Result();
		User_UserGroups uug = new User_UserGroups();
		uug.setUserId(user.getId());
			rs = userService.delUserAndUserGroups(uug);
			rs = userService.delUsers(user);
			if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
			}else{
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
			}
	}
	
	/**
	 * 删除一批用户
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/delUsers.do",produces = "application/json")
	@ResponseBody
    public Model delUsers(@RequestParam("list") List<Integer> list ,Model model){
		return model;
	}
	
	/**
	 * 分页查询用户
	 * @return
	 */	
	@RequestMapping(value = "/queryUsers.do",produces = "application/json")
	@ResponseBody
	public void queryUsers(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		int pageSize = Integer.valueOf(WebUtils.findParameterValue(request, "pageSize"));
		int pageNo = Integer.valueOf(WebUtils.findParameterValue(request, "pageNo"));
		String loginName = WebUtils.findParameterValue(request, "loginName");
		pageNo = (pageNo==0?0:((pageNo-1)*pageSize));
		Page page = new Page(pageNo,pageSize);
		Result result = userService.queryUsersByPage(page,loginName);
		Page pageResult = new Page();
		String sb = "";
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			pageResult = (Page)result.getResultValue();
			List<User> users = new ArrayList<User>();
			if(pageResult.getData()!=null){
				users = pageResult.getData();
			}
			sb = ControllerHelper.getUsersDataJsonByList(users);
		}
		String json = "{success:true,pageNo:" + pageNo + ",totalPageCount:"
		+ pageResult.getPageCount() + ",totalcount:"+pageResult.getTotalCount()+", data:[" + sb + "]}";
		//System.out.println("json#####"+json);
		AJAXUtil.writerJson(response,json);
	}
	
	/**
	 * 初始修改用户信息
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/initUpdateUserInfo.do",produces = "application/json")
	@ResponseBody
	public void initUpdateUserInfo(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		String loginName = WebUtils.findParameterValue(request, "loginName");
		Page page = new Page(0,1);
		Result result = userService.queryUsersByPage(page,loginName);
		Page pageResult = new Page();
		String userInfoStr = "";
		String userGroupInfoStr = "";
		String json = "";
		if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
			pageResult = (Page)result.getResultValue();
			List<User> users = new ArrayList<User>();
			if(pageResult.getData()!=null){
				users = pageResult.getData();
				userInfoStr = ControllerHelper.getUsersDataJsonByList(users);
				if(users.size()>0){
					User user = users.get(0);
					User_UserGroups uug = new User_UserGroups();
					uug.setUserId(user.getId());
					result = userService.selUserAndUserGroups(uug);
					if(result.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
						List<User_UserGroups> uugs = (List<User_UserGroups>)result.getResultValue();
						List<UserGroup> ugs = new ArrayList<UserGroup>();
						if(uugs!=null){
							userGroupInfoStr = ControllerHelper.getUserUserGroupsDataJsonByList(uugs);
							json = "{success:true,userInfo:["+userInfoStr+"],userGroupInfo:["+userGroupInfoStr+"]}";
						}
					}else{
						json = "{success:false,msg:\"查询用户相关用户组信息异常,请联系管理员!\" }";
					}
				}else{
					json = "{success:false,msg:\"查询用户基础信息异常,请联系管理员!\" }";
				}
			}else{
				json = "{success:false,msg:\"查询用户基础信息异常,请联系管理员!\" }";
			}
			
		}else{
			json = "{success:false,msg:\"查询用户基础信息异常,请联系管理员!\" }";
		}
		AJAXUtil.writerJson(response,json);
	}
	
	/**
	 * 用户配置用户组
	 * @param list
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/addUserUserGroups.do",method=RequestMethod.POST)
	@ResponseBody
	public void addUserUserGroups(HttpServletRequest request,HttpServletResponse response){
		AJAXUtil.setCharacterEncoding(request,response);
		int userId = Integer.valueOf(WebUtils.findParameterValue(request, "userId"));
		String userGroupIdStr =  WebUtils.findParameterValue(request, "userGroupIdStr");
		
		Result rs = new Result();
		if(userGroupIdStr!=null){
			//用户组id字符数组封装成用户组id整型集合
			List<Integer> resourceIds = new ArrayList<Integer>();
			if(userGroupIdStr.length() == 1){
				resourceIds.add(Integer.valueOf(userGroupIdStr));			
			}else{
				String [] resourceIdStrArrs = userGroupIdStr.split(",");//页面传入的资源id字符串切割获取资源id字符数组
				for(String id : resourceIdStrArrs){
					resourceIds.add(Integer.valueOf(id));
				}
			}
			//循环添加用户配置用户组
			List<User_UserGroups> list = getListCompanyResourcesByIds(userId,resourceIds);
			for(User_UserGroups uug : list){
				rs = userService.addUserAndUserGroups(uug);
			}
			
			if(rs.getResultCode()==Constants.FC_RESULT_SUCCESS_CODE){
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("true"));
			}else{
				AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
			}
		}else{
			AJAXUtil.writerJson(response,Tools.getReturnBooleanJson("false"));
		}
		
	}
	/**
	 * 通过用户及配置的用户组id封装，返回用户配置的用户组对象集合
	 * @param companyId
	 * @param resourceIds
	 * @return
	 */
	private List<User_UserGroups> getListCompanyResourcesByIds(int userId, List<Integer> userGroupIds){
		List<User_UserGroups> list= new ArrayList<User_UserGroups>();
		for(Integer userGroupId : userGroupIds){
			User_UserGroups uug = new User_UserGroups();
			uug.setUserId(userId);
			uug.setUserGroupId(userGroupId);
			list.add(uug);
		}
		return list;
	}
	
	

}
